<!--添加修改角色信息-->
<template>
    <a-modal v-model="showAddTable" :mask-closable="false" :closable="false" :width="900"
             :title="title ? '新增门禁申请' : '编辑门禁申请'"
             :maskClosable="false"
             :destroyOnClose="true">
        <a-form :form="form" @keydown.native.enter.prevent="saveApply" class="modelSearch">
          <a-form-item label="申请实验室：" prop="labId" v-bind="formStyle" required >
            <a-select
                v-decorator="['labId', { rules: [{ required: true, message: '选择实验室' }] }]"
                      placeholder="请选择实验室" v-model="labId"
                      @select="changeLabList"

            >
              <a-select-option v-for="item in labSelectList" :value="item.value"
                               :key="item.value">{{item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <!--<a-form-item v-if="!isStudent" label="申请人：" prop="stuId" v-bind="formStyle" required >-->
            <!--<a-select-->
                <!--v-decorator="['stuId', { rules: [{ required: true, message: '选择申请人' }] }]"-->
                <!--placeholder="请选择申请人" v-model="stuId"-->
                <!--@select="changeStuList"-->
            <!--&gt;-->
              <!--<a-select-option v-for="item in stuSelectList" :value="item.value"-->
                               <!--:key="item.value">{{item.label }}-->
              <!--</a-select-option>-->
            <!--</a-select>-->
          <!--</a-form-item>-->
          <a-form-item label="学生卡号：" prop="stuCardNum" v-bind="formStyle">
            <a-input
                placeholder="请输入学生卡号" ref="re"
                v-decorator="[
                        'stuCardNum',
                        {
                            rules: [
                                { required: true, message: '请输入英文、数字、@或_字符' },
                                { validator: this.verify.validateID3.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
            />
          </a-form-item>
          <a-form-item label="申请起止日期：" v-bind="formStyle" required>
            <a-date-picker
                :disabledDate="disabledStartDate"
                format="YYYY-MM-DD"
                v-model="startTime"
                placeholder="申请开始日期"
                style="width: 250px; float: left"
                v-decorator="['startTime', {required:true, rules: [{ required: true, message: '选择开始日期' }] }]"
            />
            <span style="width: 50px; text-align: center; margin-left: 20px">-</span>
            <a-date-picker
                :disabledDate="disabledEndDate"
                format="YYYY-MM-DD"
                placeholder="申请结束日期"
                v-model="endTime"
                style="width: 250px; float: right"
                v-decorator="['endTime', { rules: [{ required: true, message: '选择结束日期' }] }]"
            />
          </a-form-item>
          <a-form-item label="上传照片：" class="handFile" v-bind="formStyle"  style="position: relative" :extra="errorMsg">
            <a-input v-model="photoFileName" read-only style="width: 280px; float: left"
                     disabled :maxlength="100" placeholder="请选择图片" />
            <a href="javascript:;" style="background-color: #35bbd4 ;color: #ffffff">
              <input ref="photoFile" type="file" name="photoFile"
                     :accept="accept"
                     @change="onChangeFile($event)"
                     required />选择图片
            </a>
          </a-form-item>
          <a-form-item label="申请原因：" prop="useTo" v-bind="formStyle">
            <a-textarea
                placeholder="请输入申请原因" ref="re"
                v-decorator="[
                        'useTo',
                        {
                            rules: [
                                { required: true, message: '请输入汉字、字母、数字、_或-字符' },
                                { validator: this.verify.validateName.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
            />
          </a-form-item>
        </a-form>
        <div slot="footer">
            <a-button type="default" size="default" @click="cancelApply()">取消</a-button>
            <a-button type="primary" size="default" @click="saveApply()">确定</a-button>
        </div>
    </a-modal>
</template>

<script>
  const Base64 = require ('js-base64').Base64
    import verify from 'libs/verify'
    import AFormItem from 'ant-design-vue/es/form/FormItem'
    import moment from 'moment'
    export default {
        name: 'addEdit',
        components: {
            AFormItem,
        },
        data () {
            return {
                verify,
                form: this.$form.createForm(this),
                showAddTable: false,
                input: false,
              labObj: {},
              name: "",
              stuId: "",
              errorMsg: "",
              accept:'.png,.jpg,.jpeg,.bmp',
              photoFile:'',
              photoFileName:'',
              photoFileBase64:'',
              laboratory: "",
              stuCardNum: "",
              labId: "",
              buildName: "",
              buildCode: "",
              roomCode: "",
              startTime: "",
              endTime: "",
                isSuperAdmin:sessionStorage.getItem('user') === 'superAdmin',
                isAdmin:sessionStorage.getItem('user') === 'admin',
                isStudent:sessionStorage.getItem('roleIds').indexOf('bf87a2d6702c3ee927f113806e7a9736') > 0,
                isTeacher:sessionStorage.getItem('roleIds').indexOf('c2eb3ed226c8d4f52d9203ead594817d') > 0,
            }
        },
        computed: {
            formStyle() {
                return this.$store.state.common.formStyle
            },
          labSelectList () {
            return this.$store.state.acManage.labSelectList
          },
          stuSelectList () {
            return this.$store.state.acManage.stuSelectList
          },
        },
        props: {

            title: {
                type: Boolean,
                required: true
            },
          auth: {
            type: Boolean,
            required: false
          },
          acDTO:{
            type: Object,
            required: true
          }
        },
        watch: {

        },
        methods: {

          /**
           * 选择文件
           */
          onChangeFile (e) {
            let _this = this;
            _this.photoFile = e.target.files[0];
            _this.photoFileName = e.target.files[0].name;
            _this.errorMsg = '';
            let indexDot = _this.photoFileName.lastIndexOf('.');
            if (_this.accept.indexOf(_this.photoFileName.substr(indexDot + 1, 3).toLowerCase()) <=0) {
              _this.errorMsg = '请上传图片';
              _this.photoFile = '';
              _this.photoFileName = ''
            }else {
                let size = e.target.files[0].size
                let msize = 100*1024
                if(size > msize){
                    _this.errorMsg = '请上传不大于10K的图片';
                    _this.photoFile = '';
                    _this.photoFileName = ''
                    return
                }
              let oFReader = new FileReader();
              oFReader.readAsDataURL(_this.photoFile);
              oFReader.onloadend = function (oFRevent) {
                _this.photoFileBase64 = oFRevent.target.result.replace(/data.+?;base64,/,"")
              }
            }
          },
            /**
             * Function    : saveApply
             * Description : 打开弹框
             * Input       : none
             * Return      : none
             */
            showModal () {
                this.showAddTable = true
            },
            /**
             * Function    : showEdit
             * Description : 编辑时显示
             * Input       : opt单个所有数据
             * Return      : none
             */
            showEdit ( opt ) {
                this.showAddTable = true
                this.id = opt.recordId
              this.name = opt.name
              this.laboratory = opt.laboratory
              this.stuCardNum = opt.stuCardNum
              // this.stuId = opt.stuId
              this.labId = opt.labId
              this.buildName = opt.buildName
              this.buildCode = opt.buildCode
              this.roomCode = opt.roomCode
              this.photoFileBase64 = opt.photodata
              this.startTime = moment (opt.startTime).format ('YYYY-MM-DD')
              this.endTime =  moment (opt.endTime).format ('YYYY-MM-DD')
                this.$nextTick (() => {
                    this.form.setFieldsValue (this.$pick (opt,
                        [ 'name', 'buildName', 'buildCode','roomCode','stuCardNum','stuId','labId','laboratory','useTo','startTime','endTime' ]))
                })
            },

          changeLabList ( value ) {
              let _this = this;
              let labSelectList = _this.labSelectList;
              for (let index in labSelectList){
                if (labSelectList[index].value === value){
                  this.labObj = labSelectList[index].record
                }
              }
          },
          changeStuList ( value ) {
            let _this = this;
            let stuSelectList = _this.stuSelectList;
            for (let index in stuSelectList){
              if (stuSelectList[index].value === value){
                this.name = stuSelectList[index].record.name
                this.stuId = stuSelectList[index].record.id
              }
            }
          },

          // filterStuOption(value, option){
          //   return option.label.indexOf(value) >= 0
          // },
          // filterLabOption(value, option){
          //   return option.label.indexOf(value) >= 0
          // },

          /**
           * Function    : disabledStartDate
           * Description : 对结束时间进行限制
           * Input       : startValue
           * Return      : None
           */
          disabledStartDate ( startValue ) {
            return startValue && startValue < moment().subtract(1, 'days')
          },
          /**
           * Function    : disabledEndDate
           * Description : 对结束时间进行限制
           * Input       : endValue
           * Return      : None
           */
          disabledEndDate ( endValue ) {
            const startTime = this.startTime
            if (startTime) {
              return startTime.valueOf () >= endValue.valueOf ()
            }
            return (
                endValue && endValue < moment().subtract(1, 'days')
            )
          },

            /**
             * Function    : saveApply
             * Description : 角色信息新增、编辑保存
             * Input       : name
             * Return      : none
             */
            saveApply ( ) {
              let _this = this;
                this.form.validateFields((err, value) => {
                    if (!err) {
                        let para = {}
                        para.type = (_this.isAdmin || _this.isSuperAdmin)?'0':'1'
                        para.name = _this.name
                        para.laboratory = _this.labObj.name
                        para.stuCardNum = value.stuCardNum
                        para.useTo = value.useTo
                        // para.stuId = _this.stuId
                        para.labId = _this.labObj.recordId
                        para.buildName = _this.labObj.buildName
                        para.buildCode = _this.labObj.buildCode
                        para.roomCode = _this.labObj.roomCode
                        para.photodata = _this.photoFileBase64
                        para.startTime = moment (_this.startTime).format ('YYYY-MM-DD')
                        para.endTime =  moment (_this.endTime).format ('YYYY-MM-DD')
                      if (!_this.title){
                        para.recordId = _this.id
                      }
                      _this.$store.dispatch (this.auth?'authAct':'saveAcAct', para).then (response => {
                          if (response.code === 0) {
                            _this.cancelApply()
                            _this.$emit ('init')
                            _this.$message.success (response.message)
                          } else {
                            _this.$message.error (response.message)
                          }
                      })
                    }
                })
            },

            /**
             * Function    : cancelApply
             * Description : 取消弹出框
             * Input       : val
             * Return      : none
             */
            cancelApply ( ) {
                this.showAddTable = false
                let _this = this
              _this.photoFile = '';
              _this.photoFileName = ''
              _this.photoFileBase64 = ''
              _this.clearForm()
                setTimeout(function() {
                    _this.form.resetFields()
                }, 100)
            },
          clearForm(){
            this.labObj = {}
            this.id = ''
            this.name = ''
            this.laboratory = ''
            this.stuCardNum = ''
            this.stuId = ''
            this.labId = ''
            this.buildName = ''
            this.buildCode = ''
            this.roomCode = ''
            this.startTime =''
            this.endTime = ''
          },

          initData(){
            this.$store.dispatch ('getLabListAct', {})
            // this.$store.dispatch ('getStuListAct', {})
          }


        },

        created () {
          this.initData();
        }
    }
</script>
